<!DOCTYPE html>
<html>
  <head>
    <title>Redux basic example</title>
    <script src="https://unpkg.com/redux@latest/dist/redux.min.js"></script>
  </head>
  <body>
    <div>
      <p>
        Clicked: <span id="value">0</span> times
        <button id="increment">+</button>
        <button id="decrement">-</button>
        <button id="incrementIfOdd">Increment if odd</button>
        <button id="incrementAsync">Increment async</button>
      </p>
    </div>
    <script>
      function counter(state, action) {
        // If always return same value, e.g. 5, render() is always invorked.
        // console.log("counter():", 5);
        // return 5;

        if (typeof state === "undefined") {
          console.log("counter():", 0);
          return 0;
        }
        switch (action.type) {
          case "INCREMENT":
            console.log("counter():", state + 1);
            return state + 1;
          case "DECREMENT":
            console.log("counter():", state - 1);
            return state - 1;
          default:
            console.log("counter():", state);
            return state;
        }
      }
      var store = Redux.createStore(counter);
      var valueEl = document.getElementById("value");
      function render() {
        console.log("render():", store.getState().toString());
        valueEl.innerHTML = store.getState().toString();
      }
      render();
      store.subscribe(render);
      document
        .getElementById("increment")
        .addEventListener("click", function() {
          console.log("click +: dispatch");
          store.dispatch({ type: "INCREMENT" });
        });
      document
        .getElementById("decrement")
        .addEventListener("click", function() {
          console.log("click -: dispatch");
          store.dispatch({ type: "DECREMENT" });
        });
      document
        .getElementById("incrementIfOdd")
        .addEventListener("click", function() {
          if (store.getState() % 2 !== 0) {
            store.dispatch({ type: "INCREMENT" });
          }
        });
      document
        .getElementById("incrementAsync")
        .addEventListener("click", function() {
          setTimeout(function() {
            store.dispatch({ type: "INCREMENT" });
          }, 1000);
        });
    </script>
  </body>
</html>
